package net.zubara.esni.core.util;

/**
 * This class provides a convenent way for creating URLs with large number of
 * parameters without the need of dealing with heavy <code>String</code>
 * concatenation or <code>StringBuilder</code>s. The major benefit of using this
 * factory is that adding a parameter always returns "<code>this</code>",
 * allowing them to be chained.
 * 
 * Example usage:
 * 
 * <pre>
 * String url = UrlFactory.init("http://www.foo.com") // use the static method init() to 
 *                  .param("id", "123")               // create UrlFactory instances...
 *                  .param("admin", "true")
 *                  .param("v", "1.0")
 *                  .create();
 * </pre>
 * @author mzugno
 */
public class UrlFactory {

	private StringBuilder url;
	private boolean firstParam = true;

	private UrlFactory(StringBuilder url) {
		this.url = url;
	}

	public static UrlFactory init(String url) {
		StringBuilder sb = new StringBuilder();
		sb.append(url);
		return new UrlFactory(sb);
	}

	/**
	 * Add a parameter to the current url.
	 * 
	 * @param key
	 * @param value
	 * @return
	 */
	public UrlFactory param(String key, String value) {
		url.append(firstParam ? "?" : "&");
		url.append(key);
		url.append("=");
		url.append(value);
		firstParam = false;
		return this;
	}

	public String create() {
		return url.toString();
	}

}
